from oauth import oauth
from oauthtwitter import OAuthApi

consumer_key = '2As7ZLSVR0UreeqJjuQJsw'
consumer_secret = 'CNnBOWU0yH2B0a8J7mCsXENWsZFwpmYc1VTCQVnF94'

twitter = OAuthApi(consumer_key, consumer_secret)

# Get the temporary credentials for our next few calls
temp_credentials = twitter.getRequestToken()

# User pastes this into their browser to bring back a pin number
print(twitter.getAuthorizationURL(temp_credentials))

# Get the pin # from the user and get our permanent credentials
oauth_verifier = raw_input('What is the PIN? ')
access_token = twitter.getAccessToken(temp_credentials, oauth_verifier)

print("oauth_token: " + access_token['oauth_token'])
print("oauth_token_secret: " + access_token['oauth_token_secret'])

# Do a test API call using our new credentials
twitter = OAuthApi(consumer_key, consumer_secret, access_token['oauth_token'], access_token['oauth_token_secret'])
tweetime = time.time()
twonline = False
waittime = 60

def httpdate(now):
	stamp = time.mktime(now.timetuple())
	return formatdate(
	    timeval     = stamp,
	    localtime   = False,
	    usegmt      = True
	)

class thwread( threading.Thread ):
	def __init__(self,daft):
		threading.Thread.__init__(self)
		self.daft = daft
	def run ( self ):
		global twitter, waittime
		while True:
			time.sleep(waittime)
			print "Checking timeline"
			for update in twitter.GetFriendsTimeline(since=httpdate(datetime.datetime.now() - datetime.timedelta(0,waittime))):
				print update.GetUser()+": "+update.GetText()
				self.daft.boom(update.GetText(),update.GetUser().GetScreenName(),"twitter")


def sendtweet(update):
	global twapi
	if len(update) < 140:
		twitter.PostUpdate(update)
		print "tweet posted: "+update
	else:
		print "tweet too long"

def start(daft):
	if "twitter" in sys.argv:
		
		t = thwread(daft)
		t.start()
	return True

def tick():
	pass
def say(daft,r,who,w):
	if "twitter" in w.split(","):
		global twapi
		update = who+" "+r
		if len(update) < 140:
			twapi.PostUpdate(update)
			print "posted: "+update
		
def stop():
	pass
